﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Site.Models;

namespace Site.Controllers
{
    
    [Authorize(Roles="Administrator")]
    public class UserController : Controller
    {
        
        //
        private BMSiteDBEntities _db = new BMSiteDBEntities();


        public ActionResult Index()
        {
            //return Content("test");
            var ListIds = (from u in _db.aspnet_Users
                           where u.USER_DELETEDATE==null
                           select u.UserId);
            

            List<ProfileAdmin> model = new List<ProfileAdmin>();
            foreach (Guid m in ListIds)
            {
                model.Add(new ProfileAdmin
                {
                    users = _db.aspnet_Users.First(p => p.UserId == m),
                    memberShip = _db.aspnet_Membership.First(p => p.UserId == m),
                    /*stats = _db.STATISTIC.First(p => p.STAT_USER_ID == m)*/
                    //get role name
                    
                    roles = _db.aspnet_Roles.First(p => p.RoleId == (from r in _db.vw_aspnet_UsersInRoles 
                                                                     where r.UserId == m 
                                                                     select r.RoleId).FirstOrDefault())
                });
            }
                                 
            return View(model);
            
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(Guid id)

        {
            var UserToshow = new ProfileAdmin
                {
                    
                    users = _db.aspnet_Users.First(p => p.UserId == id),
                    memberShip = _db.aspnet_Membership.First(p => p.UserId == id),
                    stats = _db.STATISTIC.First(p => p.STAT_USER_ID == id)
                    
                };
            

            return View(UserToshow);
        }

        //
        // GET: /User/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /User/Create
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([Bind(Exclude = "UserId")] aspnet_Users UserToCreate )
        {
            //Récupérer l'id de l'application
            var appliId = (from a in _db.aspnet_Applications
                           select a.ApplicationId).First();

            if (!ModelState.IsValid)
            {
                return View();
            } 
             
            try{
                //Creation d'attributs pour l'objet user
                UserToCreate.UserId = System.Guid.NewGuid();
                UserToCreate.ApplicationId= appliId;
                UserToCreate.LastActivityDate = DateTime.Now;
                UserToCreate.IsAnonymous = false;
                UserToCreate.USER_CREATIONDATE = DateTime.Now;
                _db.AddToaspnet_Users(UserToCreate); //Insertion en base de donnée
                _db.SaveChanges(); //commit
                
                //return Content("user created and id = " + UserToCreate.UserId);
                return RedirectToAction("Index");
            }
            catch//(Exception e)
            {
                //e.ToString();
                return View();
            }
        }
        
        //
        // GET: /User/Edit/5
 
        public ActionResult Edit(Guid id)
        {
            //Chargement de l'objet et modifier
            var UserToEdit = (from u in _db.aspnet_Users
                              where id==u.UserId
                              select u).First();

            return View(UserToEdit);
        }

        //
        // POST: /User/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(aspnet_Users UsertoEdit )
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            
            try
            {
                            
                //Récupération de l'objet à modifier
                var OriginalUser = (from u in _db.aspnet_Users
                                    where u.UserId == UsertoEdit.UserId
                                    select u).First();
                //creation de données à modifier et qui ne peuvent pas être donné par l'utilisateur
                UsertoEdit.LoweredUserName = UsertoEdit.UserName.ToLower();
                UsertoEdit.LastActivityDate = DateTime.Now;
                //UsertoEdit.ApplicationId = OriginalUser.ApplicationId;
                
                _db.ApplyCurrentValues(OriginalUser.EntityKey.EntitySetName, UsertoEdit);//Mise à jour de l'objet
                
                _db.SaveChanges(); //commit

                //return Content("User changed succesfully");
                return RedirectToAction("Index");
            }
            catch// (Exception e)
            {
                //return Content(e.ToString());
                return View();
            }
        }

        //
        // GET: /User/Delete/5
 
        public ActionResult Delete(Guid id)
        {

                
            var UserToLock = (from m in _db.aspnet_Membership
                                where m.UserId == id
                                select m).First();


           //_db.DeleteObject(UserToLock);
           //return Content("user deleted id = " + id);
           return View(UserToLock);
        }

        //
        
        //Soft delete: on supprime que les droit de connexion
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(Guid id, aspnet_Membership UserToLock)
        {
            try
            {
                 UserToLock = (from m in _db.aspnet_Membership
                                  where m.UserId == id
                                  select m).First();
                // TODO: Add delete logic here
                var UserLocked = UserToLock;
                UserLocked.IsLockedOut = true;
                UserLocked.LastLockoutDate = DateTime.Now;
                _db.ApplyCurrentValues(UserToLock.EntityKey.EntitySetName, UserLocked);
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        public ActionResult UnLock(Guid id)
        {

            var UserToUnLock = (from m in _db.aspnet_Membership
                              where m.UserId == id
                              select m).First();
            var UserUnLocked = UserToUnLock;
            UserUnLocked.IsLockedOut = false;
            
            _db.ApplyCurrentValues(UserToUnLock.EntityKey.EntitySetName, UserUnLocked);
            _db.SaveChanges();
            return RedirectToAction("Index", "User");
        }

    }
}
